package com.hx.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author jxlgcmh
 * @date 2019-08-04 14:28
 */
public class FastCopyDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("=========开始拷贝========");
        fastCopy("D:\\迅雷下载\\ideaIU-2019.2.exe", "D:\\迅雷下载\\ideaIU-2019.2.2.exe");
        System.out.println("=========拷贝结束========");
    }

    public static void fastCopy(String srcPath, String destPath) throws IOException {
        FileInputStream fin = new FileInputStream(srcPath);
        FileChannel fcin = fin.getChannel();
        FileOutputStream fout = new FileOutputStream(destPath);
        FileChannel fcout = fout.getChannel();
        /**
         * 为缓冲区分配1024个字节
         */
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 20);
        while (true) {
            int read = fcin.read(buffer);
            if (read == -1) {
                break;
            }
            /**
             * 切换读写
             */
            buffer.flip();
            /**
             * 写文件
             */
            fcout.write(buffer);
            /**
             * 清空缓冲区
             */
            buffer.clear();
        }

    }
}
